"use client"
import {axios} from '../Global'
import React,{ useContext, Children, cloneElement, useState } from 'react';
import useList from '@/stores/userState';

import {useRouter } from 'next/navigation'


function GetUrlRelativePath():string{
    var url = document.location.toString();
    var arrUrl = url.split("//");
    var start = arrUrl[1].indexOf("/");
    var relUrl = arrUrl[1].substring(start);//stop省略，截取从start开始到结尾的所有字符
    if(relUrl.indexOf("?") != -1){
    relUrl = relUrl.split("?")[0];
    }
    return relUrl;
}

export default function Template({ children }:{ children: React.ReactNode }) {
    const router = useRouter()
    //const userState = useContext(LevelContext);
    const [selected, onNext] = useList([]);
    const [a,seta] = useState('b')

    if(typeof(window) == 'object'){
        
        const token = localStorage.getItem('token'); 
        const toPath = GetUrlRelativePath();
        
        //console.log(userState);
        if (!(toPath == '/login' || toPath == '/register')) {

            const token = localStorage.getItem('token'); 
            if (token === null || token === '') {
              //next('/login');
            } else {
                  axios({
                    method: 'post',
                    url:`${process.env.NEXT_PUBLIC_API_URL}/api/users/getUserData`,
                    headers:{
                      "Authorization":token
                    }
                  }).then(function (response) {
                      if(response.data.code){
                        let data = response.data.data;
                        
                        // for(let key in data){
                        //   userState.user[key] = data[key];
                        // }
                      }else{
                        //prompt('登陆失效，请重新登陆');
                        //next('/login');
                      }
                  }).catch(function (error) {
                      //prompt('无法连接服务器，请尝试');
                      //next('/login');
                      console.log(error);
                  })
            }
        }

    }

    return <div>
        {children}
    </div>
}